<template>
  <div class="chat">
    <div class="chat-wrap">
      <div class="chat-container">
        <div class="left">
          <div class="list-container">
            <div class="list">
              <div
                @click="handleChatTarget(follow.uid)"
                :class="
                  targetId === follow.uid ? 'list-item current' : 'list-item'
                "
                v-for="follow in followList"
                :key="follow.uid"
              >
                <div class="avatar-container">
                  <img :src="follow.avatar" alt="" class="avatar" />
                </div>
                <div class="info-box">
                  <div class="name">{{ follow.name }}</div>
                  <div class="desc text-ellipsis">
                    {{ follow.description }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="right">
          <div v-show="!targetId" class="placeholder">
            <div class="placeholder-img"></div>
            <div class="tip">找一个小伙伴聊天吧</div>
          </div>
          <div class="dialog">
            <div class="title"></div>
            <div class="message-box" ref="messageBoxRef">
              <div class="message-list" ref="messageListRef">
                <div v-for="message in messageList" :key="message.id">
                  <div class="message-time">
                    <span class="time">{{
                      parseDateArrayToDateString(message.createTime)
                    }}</span>
                  </div>
                  <div
                    :class="
                      message.fromId === store.userInfo?.uid
                        ? 'message-item me'
                        : 'message-item'
                    "
                  >
                    <a
                      :style="{
                        backgroundImage: `url(${
                          message.fromId === store.userInfo?.uid
                            ? message.avatar
                            : message.targetAvatar
                        })`,
                      }"
                      class="avatar"
                    >
                    </a>
                    <div class="message-text">
                      <div class="text">{{ message.message }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="send-box">
              <div class="input-box">
                <div ref="contentRef" class="editor" contenteditable></div>
              </div>
              <div class="action-box">
                <div class="word-count" style="margin-right: 1rem">
                  <span>{{ getMessageLength() }}/500</span>
                </div>
                <button @click="handleSendMessage" class="but jb-blue">
                  发送
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getFriendList } from "@/api/user";
import { getFriendChatList, removeUnreadMessageList } from "@/api/chat";
import { parseDateArrayToDateString } from "@/utils/common";
import { message } from "@/utils/message";
import userStore from "@/store/user";

const store = userStore();

const targetId = ref<number | null>(null);

const messageListRef = ref<HTMLDivElement>();

const messageBoxRef = ref<HTMLDivElement>();

const route = useRoute();
const router = useRouter();

const contentRef = ref<HTMLDivElement>();

const followList = ref<Follow[]>([]);

const messageList = ref<MessageData[]>([]);

let socket: WebSocket;

const getFriendMessageList = async (targetId: number) => {
  const result = await getFriendChatList(store.userInfo!.uid, targetId);
  if (result.data.code === 200) {
    messageList.value = result.data.data;
    messageList.value = messageList.value.sort((a, b) => {
      return (
        //@ts-ignore
        new Date(...a.createTime).getTime() -
        //@ts-ignore
        new Date(...b.createTime).getTime()
      );
    });
    await nextTick(() => {
      if (messageBoxRef.value && messageListRef.value) {
        messageBoxRef.value.scrollTo({
          top: messageListRef.value.offsetHeight,
          left: 0,
          behavior: "smooth",
        });
      }
    });
    await removeUnreadMessageList(store.userInfo!.uid, targetId);
  }
};

watch(
  () => route.query.targetId,
  (newValue, _oldValue) => {
    targetId.value = parseInt(newValue as string);
    if (targetId.value) {
      messageList.value = [];
      getFriendMessageList(targetId.value);
    }
  },
  {
    immediate: true,
  }
);

const getMessageLength = () => {
  return contentRef.value?.textContent?.length || 0;
};

const handleSendMessage = () => {
  if (store.userInfo) {
    const data = JSON.stringify({
      toId: route.query.targetId,
      message: contentRef.value?.textContent || "",
      fromId: store.userInfo.uid,
    });
    socket.send(data);
    contentRef.value && (contentRef.value.textContent = "");
    message({
      type: "success",
      duration: 2000,
      message: "发送成功",
    });
  }
};

const handleChatTarget = (uId: number) => {
  router.push({
    path: "/message/chat",
    query: {
      targetId: uId,
    },
  });
};

const handleGetFriends = async () => {
  const result = await getFriendList();
  if (result.data.code === 200) {
    followList.value = result.data.data;
  }
};

onMounted(() => {
  handleGetFriends();
  const userInfo = localStorage.getItem("userInfo");
  if (userInfo) {
    socket = new WebSocket(
      "ws://localhost:8080/webSocket?userId=" + store.userInfo?.uid
    );
  }

  socket.onmessage = (e: MessageEvent) => {
    if (e.data === "消息发送成功并且已保存") {
      getFriendMessageList(+route.query.targetId!);
    }
  };
});
</script>

<style scoped lang="scss">
.chat {
  width: 100%;
  height: 100%;
}

.chat-wrap {
  width: 100%;
  height: 100%;

  .chat-container {
    font-size: 12px;
    color: #666;
    background-color: #fff;
    -webkit-box-shadow: 0 2px 4px 0 rgba(121, 146, 185, 0.54);
    box-shadow: 0 2px 4px 0 rgba(121, 146, 185, 0.54);
    border-radius: 4px;
    height: 100%;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    position: relative;

    .left {
      width: 240px;
      border-right: 1px solid #e9eaec;
      position: relative;

      .list-container {
        position: relative;
        overflow: hidden;
        height: 100%;
        font-size: 12px;

        .list {
          display: flex;
          flex-direction: column;
          overflow: auto;
          height: 100%;

          .list-item {
            width: 100%;
            display: -webkit-box;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-orient: horizontal;
            -webkit-box-direction: normal;
            -ms-flex-direction: row;
            flex-direction: row;
            padding: 19px 24px;
            position: relative;
            cursor: pointer;

            &:hover {
              background-color: #e4e5e6;
            }

            &.current {
              background-color: #e4e5e6;
            }

            .avatar-container {
              display: block;
              width: 40px;
              height: 40px;
              border-radius: 50%;
              -ms-flex-negative: 0;
              flex-shrink: 0;
              background-size: cover;
              background-position: center;
              background-repeat: no-repeat;
              margin-right: 8px;
              position: relative;
            }

            .info-box {
              display: -webkit-box;
              display: -ms-flexbox;
              display: flex;
              -webkit-box-orient: vertical;
              -webkit-box-direction: normal;
              -ms-flex-direction: column;
              flex-direction: column;
              -webkit-box-pack: center;
              -ms-flex-pack: center;
              justify-content: center;

              .name {
                width: 126px;
                display: flex;
                -webkit-box-align: center;
                -ms-flex-align: center;
                align-items: center;
                font-size: 14px;
                min-height: 16px;
                line-height: 1;
                color: #333;
              }

              .desc {
                color: #999;
                padding: 8px 0;
                margin-bottom: -6px;
                width: 155px;
              }
            }
          }
        }
      }
    }

    .right {
      width: calc(100% - 240px);
      -webkit-box-flex: 1;
      -ms-flex: 1;
      flex: 1;

      .placeholder {
        width: 100%;
        height: 100%;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-pack: center;
        -ms-flex-pack: center;
        justify-content: center;
        -webkit-box-align: center;
        -ms-flex-align: center;
        align-items: center;
        -webkit-box-orient: vertical;
        -webkit-box-direction: normal;
        -ms-flex-direction: column;
        flex-direction: column;
        overflow: hidden;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;

        .placeholder-img {
          background-size: 402px 204px;
          margin-bottom: 32px;
          height: 204px;
          background: url(/logo.png) center/contain no-repeat;
          width: 402px;
        }

        .tip {
          color: #8896b8;
          font-size: 14px;
          line-height: 1.5em;
        }
      }

      .dialog {
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-orient: vertical;
        -webkit-box-direction: normal;
        -ms-flex-direction: column;
        flex-direction: column;
        -webkit-box-align: stretch;
        -ms-flex-align: stretch;
        align-items: stretch;
        height: 100%;

        .title {
          height: 36px;
          -ms-flex-negative: 0;
          flex-shrink: 0;
          display: -webkit-box;
          display: -ms-flexbox;
          display: flex;
          -webkit-box-pack: center;
          -ms-flex-pack: center;
          justify-content: center;
          -webkit-box-align: center;
          -ms-flex-align: center;
          align-items: center;
          border-bottom: 1px solid #e9eaec;
          position: relative;
          text-align: center;
          color: #333;
        }

        .message-box {
          -webkit-box-flex: 1;
          -ms-flex: 1;
          flex: 1;
          position: relative;
          overflow-x: hidden;
          overflow-y: scroll;

          .message-list {
            overflow: auto;
            background-color: #f4f5f7;
            min-height: 100% !important;

            .message-time {
              padding: 16px 0 16px;
              text-align: center;
            }

            .message-item {
              min-height: 48px;
              padding: 0 16px 16px;
              overflow: hidden;
              position: relative;
              margin-top: 1rem;

              .avatar {
                display: block;
                width: 30px;
                height: 30px;
                border-radius: 50%;
                -ms-flex-negative: 0;
                flex-shrink: 0;
                background-size: cover;
                background-position: center;
                background-repeat: no-repeat;
                float: left;
              }

              .message-text {
                max-width: 480px;
                margin: 0 10px;
                position: relative;
                overflow: hidden;
                color: #333;
                float: left;

                .text {
                  line-height: 1.5;
                  font-size: 14px;
                  min-height: 37px;
                  padding: 8px 16px;
                  word-wrap: break-word;
                  word-break: break-word;
                  border-radius: 0 16px 16px 16px;
                  overflow: hidden;
                  background: #fff;
                  position: relative;
                  z-index: 1;
                }
              }
            }

            .message-item.me {
              .avatar {
                float: right;
              }

              .message-text {
                float: right;

                .text {
                  background: #80b9f2;
                  border-radius: 16px 0 16px 16px;
                }
              }
            }
          }
        }

        .send-box {
          height: 162px;
          border-top: 1px solid #d8d8d8;
          border-bottom-right-radius: 4px;
          -ms-flex-negative: 0;
          flex-shrink: 0;
          padding: 0 16px;
          position: relative;
          z-index: 2;

          .input-box {
            position: relative;

            .editor {
              height: 120px;
              width: 100%;
              min-height: 120px;
              max-height: 300px;
              letter-spacing: 1px;
              padding-top: 10px;
              -webkit-box-sizing: border-box;
              box-sizing: border-box;
              white-space: pre-wrap;
              overflow-x: hidden;
              overflow-y: auto;
              color: #222;
              font-size: 14px;
              vertical-align: baseline;
              outline: none;
              line-height: normal;
              border-radius: 4px;
              word-break: break-word;
              word-wrap: break-word;
            }
          }

          .action-box {
            justify-content: flex-end;
            height: 46px;
            display: flex;
            -webkit-box-pack: end;
            align-items: center;
          }
        }
      }
    }
  }
}
</style>
